//
//  SearchGymAddressViewController.m
//  YunDongGym
//
//  Created by lqq on 2018/7/17.
//  Copyright © 2018年 lqq. All rights reserved.
//

#import "SearchGymAddressViewController.h"
#import "WGS84TOGCJ02.h"
#import "I_Gym.h"
@interface SearchGymAddressViewController ()<UITableViewDataSource,UITableViewDelegate,CLLocationManagerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *navBackViewHeightContraint;
@property (weak, nonatomic) IBOutlet UIView *searchBackView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, assign) SearchGYMAddressType searchType;
@property (nonatomic, strong) NSArray *searchResults;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;//经纬度
@property(nonatomic ,strong) NSString *city;
@end

@implementation SearchGymAddressViewController


#pragma mark Class Method
+ (instancetype)controllerWithSearchType:(SearchGYMAddressType)searchType
{
    SearchGymAddressViewController *vc = [UIStoryboard controllerWithStoryBoardIdentify:NSStringFromClass([SearchGymAddressViewController class]) inStoryBoard:@"GymManagement"];
    vc.searchType = searchType;
    return vc;
}

#pragma mark Life Circle
- (void)viewDidLoad {
    [super viewDidLoad];
    _navBackViewHeightContraint.constant = [Toolkit getSystemNavHeight];
    _searchBackView.layer.cornerRadius = 15;
    _searchBackView.layer.masksToBounds = YES;
    _tableView.tableFooterView = [UIView new];
    _tableView.backgroundColor = TP.controllerBackColor;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _textField.delegate = self;
    [_textField becomeFirstResponder];
    [_textField addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    
    if (_searchType == SearchGYMAddressType_SearchName) {
        _textField.placeholder = @"搜索所在健身房";
    } else {
        _textField.placeholder = @"搜索地址";
    }
    
    [self configLocationManager];
}


#pragma mark NET
- (void)searchGymWithStr:(NSString *)str
{
    
    NSString *address;
    NSString *name;
    if (_searchType == SearchGYMAddressType_SearchAddress) {
        address = _textField.text;
    } else {
        name = _textField.text;
    }
    NSLog(@"%@",address);
    WeakSelf(self);
    [I_Gym searchGymByAddress:address gymName:name city:_city latitude:_coordinate.latitude longitude:_coordinate.longitude success:^(NSArray *list) {
        [weakself.tableView hideStatusView];

        weakself.searchResults = list;
        [weakself.tableView reloadData];
        if (weakself.searchType == SearchGYMAddressType_SearchName) {
            //添加footer
            UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kDeviceWidth, 75)];
            UILabel *label = [footerView addCenterLabelWithText:@"没有你的健身房？点击新增" textColor:HEXColor(@"#9B9B9B") font:RegularFont(14)];
            label.userInteractionEnabled = YES;
            weakself.tableView.tableFooterView = footerView;
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:@"没有你的健身房？点击新增"];
            [attStr setAttributes:@{NSForegroundColorAttributeName:HEXColor(@"#3AA7FF")} range:NSMakeRange(8, 4)];
            label.attributedText = attStr;
            UITapGestureRecognizer *addAddressTap = [[UITapGestureRecognizer alloc] initWithTarget:weakself action:@selector(addAddressTapClicked)];
            [label addGestureRecognizer:addAddressTap];
        }
    } failure:^(NSError *error) {
        [AV showError:error];
    }];
}

#pragma mark Pravite
- (void)configLocationManager
{
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
    if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [_locationManager requestWhenInUseAuthorization];
        [_locationManager requestAlwaysAuthorization];
    }
    _locationManager.delegate = self;
    [_locationManager startUpdatingLocation];
}


#pragma mark Action

- (IBAction)cancleBtnClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addAddressTapClicked
{
    M_Gym *gym = [[M_Gym alloc] init];
    gym.gymName = _textField.text;
    if (_choiceBlock) {
        _choiceBlock(gym);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _searchResults.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchGYMCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SearchGYMCell class])];
    M_Gym *gym = _searchResults[indexPath.row];
    cell.nameLabel.text = gym.gymName;
    cell.addressLabel.text = gym.gymAddress;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    M_Gym *gym = _searchResults[indexPath.row];
    if (_choiceBlock) {
        _choiceBlock(gym);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

#pragma mark UITextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length == 0) {
        [AV showRemind:@"请输入关键字"];
        return NO;
    }
    [self searchGymWithStr:textField.text];
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - KVO
- (void)textFieldChanged:(UITextField *)textField
{
    if (textField.text > 0) {
        [self searchGymWithStr:textField.text];
    }
    
}


#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    //    NSLog(@"CLLocation对象包含的位置数据的数组%@",locations);
    CLLocation *newLocation = [locations lastObject];
    if (newLocation) {
        [_locationManager stopUpdatingLocation];
        _locationManager.delegate = nil;
        CLLocationCoordinate2D coordinate = newLocation.coordinate;
        if (![WGS84TOGCJ02 isLocationOutOfChina:newLocation.coordinate]) {
            CLLocationCoordinate2D newCoordinate = [WGS84TOGCJ02 transformFromWGSToGCJ:newLocation.coordinate];
            coordinate.longitude = newCoordinate.longitude;
            coordinate.latitude = newCoordinate.latitude;
        }
        
        self.coordinate = coordinate;
        
        
        double longitude = coordinate.longitude;
        double latitude = coordinate.latitude;
        NSLog(@"经度 %f  纬度 %f",longitude,latitude);
        CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude
                                                          longitude:longitude];
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
            CLPlacemark *placemark = placemarks[0];
            NSString *city = [placemark.addressDictionary[@"City"] length] > 0 ? placemark.addressDictionary[@"City"] : @"未知";
            NSString *subLocality = [placemark.addressDictionary[@"SubLocality"] length] > 0 ? placemark.addressDictionary[@"SubLocality"] : @"未知";
            NSString *thoroughfare = [placemark.addressDictionary[@"Thoroughfare"] length] > 0 ? placemark.addressDictionary[@"Thoroughfare"] : @"未知";
            NSString *address = [NSString stringWithFormat:@"%@%@%@%@", city, subLocality, thoroughfare, placemark.addressDictionary[@"SubThoroughfare"]];
            address = [address stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
            NSLog(@"address:%@",address);
            if (city.length > 0) {
                self.city = city;
            }
            
        }];
        
    }
    
    
}




- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    
    [_locationManager stopUpdatingLocation];
    _locationManager.delegate = nil;
    CLLocationCoordinate2D coordinate;
    coordinate.longitude = 0.00;
    coordinate.latitude = 0.00;
    self.coordinate = coordinate;
    
}


- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (status == kCLAuthorizationStatusNotDetermined) {
        if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [manager requestWhenInUseAuthorization];
            [manager requestAlwaysAuthorization];
        }
    } else if (status < kCLAuthorizationStatusDenied) {
        
    } else {
        
    }
}

@end



@implementation SearchGYMCell

-(void)awakeFromNib
{
    [super awakeFromNib];
    [self.contentView addBottomLineViewWithLeftSpace:0 rightSpace:0];
}
@end
